import React, { useState, memo, useEffect, useContext } from "react";
// import "./index.scss";
import { MyPrizeWrapper } from "./style";
import { Mask, InfiniteScroll } from "antd-mobile";

import { miniProgram } from "weixin-js-sdk";
import { getDrawPrizeMgData } from "@Services/api";
import { baseURL } from "@Services";

import { isMiniProgram } from "@Utils";

import ContextApp from "@Pages/context";

const IndexBox = memo((props) => {
  const Consumer = useContext(ContextApp);
  const [visible, setVisible] = useState(false);
  const [MyPrizeData, setMyPrizeData] = useState([]);
  const [page, setPage] = useState(1);
  const [BeginTimestamp, setBeginTimestamp] = useState(0);
  const [hasMore, setHasMore] = useState(true);

  useEffect(() => {
    setVisible(Consumer.isShow_MyPrize);
  }, [Consumer.isShow_MyPrize]);

  async function net_GetDrawPrizeMgData(page) {
    let params = {
      page,
      pageSize: 20,
      phone: Consumer.mobile,
      id: Consumer.activeId,
    };

    return await getDrawPrizeMgData(params);
  }

  // 关闭蒙层
  function closeMask() {
    Consumer.handleShowMyPrize(false);
  }

  async function loadMore() {
    if (BeginTimestamp + 2000 > new Date().getTime()) return false;
    setBeginTimestamp(new Date().getTime());

    const { code, data } = await net_GetDrawPrizeMgData(page);
    if (code == 200) {
      setMyPrizeData((val) => [...val, ...data]);
      setHasMore(data.length > 0);
      const newPage = page + 1;
      setPage(newPage);
    }
  }

  const InfiniteScrollContent = memo(({ hasMore }: { hasMore?: boolean }) => {
    return (
      <div className={`LoadingEnd ${MyPrizeData.length < 5 ? "loadEnd" : ""}`}>
        {hasMore ? (
          <>
            <span style={{ color: "#ce99ff" }}>Loading</span>
          </>
        ) : (
          <span
            style={{ color: "#ce99ff" }}
            className={`${MyPrizeData.length < 8 ? "displaynone" : null}`}
          >
            --- 到底啦 ---
          </span>
        )}
      </div>
    );
  });

  var baseUrl = `${baseURL}/cloudH5/#/`;
  let param_mobile = `mobile=${Consumer.mobile}`;

  // 首页
  const goIndexPage = () => {
    if (isMiniProgram()) {
      miniProgram.switchTab({
        url: "/pages/index/index",
      });
    } else {
      return (window.location.href = `${baseUrl}index?deviceCode=${Consumer.deviceCode}&code=${props.openId}&payMode=${props.clientType}&from=reactPrize&${param_mobile}`);
    }
  };

  // 福利页
  const goWealPage = () => {
    if (isMiniProgram()) {
      miniProgram.switchTab({
        url: "/pages/weal/index",
      });
    } else {
      return (window.location.href = `${baseUrl}fulishe/${param_mobile}`);
    }
  };

  // 兑换
  const goOrderListPage = (sonumber = "") => {
    if (isMiniProgram()) {
      miniProgram.navigateTo({
        url: "/package-order/pages/orderSuccess/index?sonumber=" + sonumber,
      });
    } else {
      return (window.location.href = `${baseUrl}fulishe/exchangedetail?sonumber=${sonumber}&${param_mobile}`);
    }
  };

  // 商城
  const goShopPage = (sonumber = "") => {
    if (isMiniProgram()) {
      miniProgram.navigateTo({
        url: "/package-order/pages/orderSuccess/index?sonumber=" + sonumber,
      });
    } else {
      // todo
      return (window.location.href = `${baseUrl}shoppingDetail?sonumber=${sonumber}&${param_mobile}`);
    }
  };

  return (
    <Mask visible={visible} onMaskClick={() => closeMask(false)}>
      <MyPrizeWrapper>
        <div className={`myPrizeBox ${MyPrizeData.length == 0 && "empty"}`}>
          <div className="myPrizeList">
            <>
              {MyPrizeData.map((v) => {
                return (
                  <div className="myPrizeItem" key={v.id}>
                    <div>
                      <p className="myPrizeName noWrap">{v.name}</p>
                      <p className="myPrizeTime">{v.createTime}</p>
                    </div>
                    <div className="myPrizeBtn">
                      {(() => {
                        switch (v.goodsType) {
                          case 1:
                            return (
                              <span onClick={() => goIndexPage()}>去使用</span>
                            );

                          case 2:
                            return (
                              <span onClick={() => goIndexPage()}>去使用</span>
                            );

                          case 3:
                            return (
                              <span onClick={() => goIndexPage()}>去使用</span>
                            );

                          case 4:
                            return (
                              <span onClick={() => goOrderListPage(v.sonumber)}>
                                去查看
                              </span>
                            );

                          case 5:
                            return;

                          case 6: // 6实物
                            return (
                              <span onClick={() => goShopPage(v.sonumber)}>
                                去查看
                              </span>
                            );

                          case 7:
                            return (
                              <span onClick={() => goWealPage()}>去兑换</span>
                            );

                          default:
                            return null;
                        }
                      })()}
                    </div>
                  </div>
                );
              })}
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
                {MyPrizeData.length > 0 ? (
                  <InfiniteScrollContent />
                ) : (
                  <h2 className="MyPrize_Empty">暂无中奖记录</h2>
                )}
              </InfiniteScroll>
            </>
          </div>
          <div
            className="MaskCloseIcon"
            style={{ top: "-9vh", right: 0 }}
            onClick={() => closeMask(false)}
          ></div>
        </div>
      </MyPrizeWrapper>
    </Mask>
  );
});

export default IndexBox;
